package com.cmcc.linlaker.ui.upload.fragment;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.android.volley.VolleyError;
import com.cmcc.linlaker.R;
import com.cmcc.linlaker.application.LinhuApp;
import com.cmcc.linlaker.bean.BaseBean;
import com.cmcc.linlaker.bean.DictBean;
import com.cmcc.linlaker.bean.ImageUploadBean;
import com.cmcc.linlaker.crop.ClipImageActivity;
import com.cmcc.linlaker.crop.util.ActivityResultHelper;
import com.cmcc.linlaker.fragment.RoundFragment;
import com.cmcc.linlaker.http.ApiDefine;
import com.cmcc.linlaker.permission.GPermisson;
import com.cmcc.linlaker.permission.PermissionCallback;
import com.cmcc.linlaker.ui.query.ImageScanActivity;
import com.cmcc.linlaker.ui.query.ProjectListActivity;
import com.cmcc.linlaker.ui.query.bean.QueryProjectBean;
import com.cmcc.linlaker.ui.upload.UploadSelfDealDetailActivity;
import com.cmcc.linlaker.ui.upload.UploadSuccessActivity;
import com.cmcc.linlaker.ui.upload.adapter.ImageAdapter;
import com.cmcc.linlaker.ui.upload.bean.ImageBean;
import com.cmcc.linlaker.utils.DensityUtil;
import com.cmcc.linlaker.utils.IntentUtils;
import com.cmcc.linlaker.utils.PhotoUtils;
import com.cmcc.linlaker.utils.PictureUtil;
import com.cmcc.linlaker.utils.SPHelper;
import com.cmcc.linlaker.utils.StringUtils;
import com.cmcc.linlaker.utils.ToastUtils;
import com.cmcc.linlaker.utils.Utils;
import com.cmcc.linlaker.view.GridSpacingItemDecoration;
import com.cmcc.linlaker.volley.GsonRequestHelper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.tianditu.android.maps.GeoPoint;
import com.tianditu.android.maps.MapView;
import com.tianditu.android.maps.MyLocationOverlay;
import com.tianditu.android.maps.OnGetPoiResultListener;
import com.tianditu.android.maps.PoiInfo;
import com.tianditu.android.maps.PoiSearch;
import com.tianditu.android.maps.TErrorCode;
import com.tianditu.android.maps.TGeoAddress;
import com.tianditu.android.maps.TGeoDecode;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zyyoona7.wheel.WheelView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class UploadProjectFragment extends Fragment {
    private View fragmentView;

    public static UploadProjectFragment newInstance() {
        UploadProjectFragment fragment = new UploadProjectFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.fragment_upload_project, container, false);
        initView();
        return fragmentView;
    }

    private ImageAdapter adapter;
    private List<ImageBean> bmpList = new ArrayList<>();
    private RecyclerView recycler_pic;

    private TextView text_project_name, text_input_info, textRegion, text_small_type, text_big_type;
    private EditText edit_address, edit_title, edit_description;

    private TextView text_before_deal_pic;

    private ImageView image_before_far_1, image_before_near_1;
    private ImageView image_after_far_1, image_after_near_1;

    private EditText edit_remark;
    private RecyclerView recycler_after_pic;
    private ImageAdapter afterAdapter;
    private List<ImageBean> bmpAfterList = new ArrayList<>();

    private void initView() {
        edit_remark = fragmentView.findViewById(R.id.edit_remark);
        recycler_after_pic = fragmentView.findViewById(R.id.recycler_after_pic);
        setAfterRecyclerView(recycler_after_pic, bmpAfterList);
        addButton2();

        text_before_deal_pic = fragmentView.findViewById(R.id.text_before_deal_pic);
        textRegion = fragmentView.findViewById(R.id.textRegion);
        text_small_type = fragmentView.findViewById(R.id.text_small_type);
        text_big_type = fragmentView.findViewById(R.id.text_big_type);

        recycler_pic = fragmentView.findViewById(R.id.recycler_pic);
        setRecyclerView(recycler_pic, bmpList);
        addButton();

        text_input_info = fragmentView.findViewById(R.id.text_input_info);
        edit_address = fragmentView.findViewById(R.id.edit_address);
        text_project_name = fragmentView.findViewById(R.id.text_project_name);
        edit_title = fragmentView.findViewById(R.id.edit_title);
        edit_description = fragmentView.findViewById(R.id.edit_description);
        edit_description.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String content = edit_description.getText().toString();
                int length = content.length();
                text_input_info.setText(length + "/100");
            }
        });

        image_before_far_1 = fragmentView.findViewById(R.id.image_before_far_1);
        image_before_near_1 = fragmentView.findViewById(R.id.image_before_near_1);
        image_after_far_1 = fragmentView.findViewById(R.id.image_after_far_1);
        image_after_near_1 = fragmentView.findViewById(R.id.image_after_near_1);

        fragmentView.findViewById(R.id.layoutConnectedProject).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectProjectType();
            }
        });
        fragmentView.findViewById(R.id.text_upload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upload();
            }
        });
        fragmentView.findViewById(R.id.layout_address_icon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getLocationInfo();
            }
        });

        fragmentView.findViewById(R.id.layoutBigType).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDict(fragmentView.findViewById(R.id.layout_problem), "big");
            }
        });

        fragmentView.findViewById(R.id.layoutSmallType).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(text_big_type.getText().toString())) {
                    showDict(fragmentView.findViewById(R.id.layout_problem), "small");
                } else {
                    ToastUtils.showText(getActivity(), "请先选择问题大类");
                }
            }
        });

        fragmentView.findViewById(R.id.layout_before_far_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                index = 0;
                selectPicturesIndex(0);
            }
        });

        fragmentView.findViewById(R.id.layout_before_near_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                index = 1;
                selectPicturesIndex(1);
            }
        });

        fragmentView.findViewById(R.id.layout_after_far_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                index = 2;
                selectPicturesIndex(2);
            }
        });

        fragmentView.findViewById(R.id.layout_after_near_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                index = 3;
                selectPicturesIndex(3);
            }
        });

        fragmentView.findViewById(R.id.layout_no_self_deal).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isSelfDeal) {
                    isSelfDeal = false;
                    ((ImageView) fragmentView.findViewById(R.id.image_no_self_deal)).setImageResource(R.mipmap.login_cb_checked);
                    ((ImageView) fragmentView.findViewById(R.id.image_yes_self_deal)).setImageResource(R.mipmap.login_cb_unchecked);
                    text_before_deal_pic.setText("拍摄照片");
                    fragmentView.findViewById(R.id.text_before_deal_pic1).setVisibility(View.GONE);
//                    fragmentView.findViewById(R.id.layout_before_1).setVisibility(View.GONE);
                    fragmentView.findViewById(R.id.layout_after).setVisibility(View.GONE);
                }
            }
        });

        fragmentView.findViewById(R.id.layout_yes_self_deal).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isSelfDeal) {
                    isSelfDeal = true;
                    ((ImageView) fragmentView.findViewById(R.id.image_no_self_deal)).setImageResource(R.mipmap.login_cb_unchecked);
                    ((ImageView) fragmentView.findViewById(R.id.image_yes_self_deal)).setImageResource(R.mipmap.login_cb_checked);
//                    text_before_deal_pic.setText("处置前照片 (请至少上传一张近景照片和一张远景照片)");

                    text_before_deal_pic.setText("处置前照片");
                    fragmentView.findViewById(R.id.text_before_deal_pic1).setVisibility(View.VISIBLE);

//                    fragmentView.findViewById(R.id.layout_before_1).setVisibility(View.VISIBLE);
                    fragmentView.findViewById(R.id.layout_after).setVisibility(View.VISIBLE);
                }
            }
        });


//        fragmentView.findViewById(R.id.layoutRegion).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                showDict(fragmentView.findViewById(R.id.layout_problem), "region");
//            }
//        });

//        getProblemNumber();

        getGpsInfo();
    }

    private boolean isSelfDeal = false;

    /**
     * 获取经纬度
     */
    private void getGpsInfo() {
        getCurrentLocationLatLng();
//        GPermisson.with(getActivity())
//                .permisson(new String[]{Manifest.permission.ACCESS_FINE_LOCATION})
//                .callback(new PermissionCallback() {
//                    @Override
//                    public void onPermissionGranted() {
//                        getCurrentLocationLatLng();
//                    }
//
//                    @Override
//                    public void shouldShowRational(String permisson) {
//                        //禁止
//                    }
//
//                    @Override
//                    public void onPermissonReject(String permisson) {
//                    }
//                }).request();
    }


    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    /**
     * 初始化定位并设置定位回调监听
     */
    private void getCurrentLocationLatLng() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getActivity());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        // 同时使用网络定位和GPS定位,优先返回最高精度的定位结果,以及对应的地址描述信息
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。默认连续定位 切最低时间间隔为1000ms
        mLocationOption.setOnceLocation(false);
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    private String currentPlaceName;

    /**
     * 定位回调监听器
     */
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    latitude = amapLocation.getLatitude();//获取纬度
                    longitude = amapLocation.getLongitude();//获取经度
                    amapLocation.getAccuracy();//获取精度信息

                    currentPlaceName = amapLocation.getAddress();
                    textRegion.setText(amapLocation.getDistrict());
                } else {
                    Toast.makeText(getActivity(), "为正常使用，请开启定位服务", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    /**
     * 上报
     */
    public void upload() {
        String address = edit_address.getText().toString();
        if (latitude != 0 && longitude != 0) {
            uploadData();
        } else {
            getLatLng(address);
        }

    }

    private void setAfterRecyclerView(final RecyclerView recycler_view, final List<ImageBean> itemList) {
        recycler_view.setHasFixedSize(true);
        recycler_view.setLayoutManager(new GridLayoutManager(getActivity(), 4));

        recycler_view.setNestedScrollingEnabled(false);
        recycler_view.addItemDecoration(new GridSpacingItemDecoration(4, DensityUtil.dip2px(getActivity(), 10), true));
        afterAdapter = new ImageAdapter(getActivity(), itemList);
        afterAdapter.setOnItemClickListener(new ImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (itemList.get(position).type == 0) {
                    selectPictures2();
                } else {
                    Intent intent = new Intent(getActivity(), ImageScanActivity.class);
                    intent.putExtra("imageBeanList", imageAfterList);
                    intent.putExtra("position", position);
                    startActivity(intent);
                }
            }

            @Override
            public void onItemDeleteClick(int position) {
                deletePic2(position);
            }
        });
        recycler_view.setAdapter(afterAdapter);
    }


    private void setRecyclerView(final RecyclerView recycler_view, final List<ImageBean> itemList) {
        recycler_view.setHasFixedSize(true);
        recycler_view.setLayoutManager(new GridLayoutManager(getActivity(), 4));

        recycler_view.setNestedScrollingEnabled(false);
        recycler_view.addItemDecoration(new GridSpacingItemDecoration(4, DensityUtil.dip2px(getActivity(), 10), true));
        adapter = new ImageAdapter(getActivity(), itemList);
        adapter.setOnItemClickListener(new ImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (itemList.get(position).type == 0) {
                    selectPictures();
                } else {
                    Intent intent = new Intent(getActivity(), ImageScanActivity.class);
                    intent.putExtra("imageBeanList", imageList);
                    intent.putExtra("position", position);
                    startActivity(intent);
                }
            }

            @Override
            public void onItemDeleteClick(int position) {
                deletePic(position);
            }
        });
        recycler_view.setAdapter(adapter);
    }


    /**
     * 选择图片
     */
    public void selectPicturesIndex(final int index) {
        if (Build.VERSION.SDK_INT >= 23) {
            GPermisson.with(getActivity())
                    .permisson(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
                    .callback(new PermissionCallback() {
                        @Override
                        public void onPermissionGranted() {
                            showSelectDialogIndex(index);
                        }

                        @Override
                        public void shouldShowRational(String permisson) {
                        }

                        @Override
                        public void onPermissonReject(String permisson) {
                        }
                    }).request();
        } else {
            showSelectDialogIndex(index);
        }
    }

    private int index = 0;
    public static final int[] RC_TAKE_PHOTO_ARR = {100, 200, 300, 400};
    public static final int[] RC_CHOOSE_PHOTO_ARR = {101, 201, 301, 401};
    public static final int[] RC_CROP_PHOTO_ARR = {102, 202, 302, 402};

    private File[] fileUriArr = {new File(Environment.getExternalStorageDirectory().getPath() + "/lh_photo_1.jpg"),
            new File(Environment.getExternalStorageDirectory().getPath() + "/lh_photo_2.jpg"),
            new File(Environment.getExternalStorageDirectory().getPath() + "/lh_photo_3.jpg"),
            new File(Environment.getExternalStorageDirectory().getPath() + "/lh_photo_4.jpg")};
    private File[] fileCropUriArr = {new File(Environment.getExternalStorageDirectory().getPath() + "/lh_crop_photo_1.jpg"),
            new File(Environment.getExternalStorageDirectory().getPath() + "/lh_crop_photo_2.jpg"),
            new File(Environment.getExternalStorageDirectory().getPath() + "/lh_crop_photo_3.jpg"),
            new File(Environment.getExternalStorageDirectory().getPath() + "/lh_crop_photo_4.jpg")};
    private Uri[] imageUriArr = new Uri[4];
    private Uri[] cropImageUriArr = new Uri[4];


    private void showSelectDialogIndex(final int index) {
        final String[] items = {"相机", "相册"};
        AlertDialog.Builder builder = new AlertDialog.Builder(
                getActivity());
        builder.setTitle("选择图片")
                .setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (which == 0) {// 相机
                            takePhotoIndex(index);
                        } else if (which == 1) {// 相册
                            choosePhotoIndex(index);
                        }

                    }
                }).create().show();
    }

    /**
     * 拍照
     */
    private void takePhotoIndex(int index) {
        imageUriArr[index] = Uri.fromFile(fileUriArr[index]);
        //通过FileProvider创建一个content类型的Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUriArr[index] = FileProvider.getUriForFile(getActivity(), "com.cmcc.linlaker.fileprovider", fileUriArr[index]);
        }

        PhotoUtils.fragmentTakePicture(this, imageUriArr[index], RC_TAKE_PHOTO_ARR[index]);
    }

    /**
     * 打开相册
     */
    private void choosePhotoIndex(int index) {
        PhotoUtils.fragmentOpenPic(this, RC_CHOOSE_PHOTO_ARR[index]);
    }

    /**
     * 选择图片
     */
    public void selectPictures2() {
        if (Build.VERSION.SDK_INT >= 23) {
            GPermisson.with(getActivity())
                    .permisson(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
                    .callback(new PermissionCallback() {
                        @Override
                        public void onPermissionGranted() {
                            showSelectDialog2();
                        }

                        @Override
                        public void shouldShowRational(String permisson) {
                        }

                        @Override
                        public void onPermissonReject(String permisson) {
                        }
                    }).request();
        } else {
            showSelectDialog2();
        }
    }

    private void showSelectDialog2() {
        final String[] items = {"相机", "相册"};
        AlertDialog.Builder builder = new AlertDialog.Builder(
                getActivity());
        builder.setTitle("选择图片")
                .setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (which == 0) {// 相机
                            takePhoto2();
                        } else if (which == 1) {// 相册
                            choosePhoto2();
                        }

                    }
                }).create().show();
    }


    public static final int RC_TAKE_PHOTO2 = 1000;
    public static final int RC_CHOOSE_PHOTO2 = 2000;
    public static final int RC_CROP_PHOTO2 = 3000;

    private File fileUri2 = new File(Environment.getExternalStorageDirectory().getPath() + "/lh_photo2.jpg");
    private File fileCropUri2 = new File(Environment.getExternalStorageDirectory().getPath() + "/lh_crop_photo2.jpg");
    private Uri imageUri2;
    private Uri cropImageUri2;

    /**
     * 拍照
     */
    private void takePhoto2() {
        imageUri2 = Uri.fromFile(fileUri2);
        //通过FileProvider创建一个content类型的Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri2 = FileProvider.getUriForFile(getActivity(), "com.cmcc.linlaker.fileprovider", fileUri2);
        }

        PhotoUtils.fragmentTakePicture(this, imageUri2, RC_TAKE_PHOTO2);
    }

    /**
     * 打开相册
     */
    private void choosePhoto2() {
        PhotoUtils.fragmentOpenPic(this, RC_CHOOSE_PHOTO2);
    }

    /**
     * 选择图片
     */
    public void selectPictures() {
        if (Build.VERSION.SDK_INT >= 23) {
            GPermisson.with(getActivity())
                    .permisson(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
                    .callback(new PermissionCallback() {
                        @Override
                        public void onPermissionGranted() {
                            showSelectDialog();
                        }

                        @Override
                        public void shouldShowRational(String permisson) {
                        }

                        @Override
                        public void onPermissonReject(String permisson) {
                        }
                    }).request();
        } else {
            showSelectDialog();
        }
    }

    private void showSelectDialog() {
        final String[] items = {"相机", "相册"};
        AlertDialog.Builder builder = new AlertDialog.Builder(
                getActivity());
        builder.setTitle("选择图片")
                .setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (which == 0) {// 相机
                            takePhoto();
                        } else if (which == 1) {// 相册
                            choosePhoto();
                        }

                    }
                }).create().show();
    }


    public static final int RC_TAKE_PHOTO = 1;
    public static final int RC_CHOOSE_PHOTO = 2;
    public static final int RC_CROP_PHOTO = 3;

    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/lh_photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/lh_crop_photo.jpg");
    private Uri imageUri;
    private Uri cropImageUri;

    /**
     * 拍照
     */
    private void takePhoto() {
        imageUri = Uri.fromFile(fileUri);
        //通过FileProvider创建一个content类型的Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(getActivity(), "com.cmcc.linlaker.fileprovider", fileUri);
        }

        PhotoUtils.fragmentTakePicture(this, imageUri, RC_TAKE_PHOTO);
    }

    /**
     * 打开相册
     */
    private void choosePhoto() {
        PhotoUtils.fragmentOpenPic(this, RC_CHOOSE_PHOTO);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == RC_TAKE_PHOTO) {
                gotoClipActivity(Uri.fromFile(fileUri));
            } else if (requestCode == RC_CHOOSE_PHOTO) {
                cropImageUri = Uri.fromFile(fileCropUri);
                gotoClipActivity(data.getData());
            } else if (requestCode == RC_CROP_PHOTO) {
                Bitmap myBitmap = PhotoUtils.getBitmapFromUri(cropImageUri, getActivity());
                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
                PictureUtil.saveMyBitmap(myBitmap, file);

                addBmp(myBitmap);
                uploadPic(fileName + ".png", file);
            } else if (requestCode == RC_TAKE_PHOTO_ARR[index]) {
                gotoClipActivityIndex(Uri.fromFile(fileUriArr[index]));
            } else if (requestCode == RC_CHOOSE_PHOTO_ARR[index]) {
                cropImageUriArr[index] = Uri.fromFile(fileCropUriArr[index]);
                gotoClipActivityIndex(data.getData());
            } else if (requestCode == RC_CROP_PHOTO_ARR[index]) {
                Bitmap myBitmap = PhotoUtils.getBitmapFromUri(cropImageUriArr[index], getActivity());

                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
                PictureUtil.saveMyBitmap(myBitmap, file);

                dealBmp(myBitmap);
                uploadPicIndex(fileName + ".png", file);
            } else if (requestCode == RC_TAKE_PHOTO2) {
                gotoClipActivity2(Uri.fromFile(fileUri2));
            } else if (requestCode == RC_CHOOSE_PHOTO2) {
                cropImageUri2 = Uri.fromFile(fileCropUri2);
                gotoClipActivity2(data.getData());
            } else if (requestCode == RC_CROP_PHOTO2) {
                Bitmap myBitmap = PhotoUtils.getBitmapFromUri(cropImageUri2, getActivity());
                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
                PictureUtil.saveMyBitmap(myBitmap, file);

                addBmp2(myBitmap);
                uploadPic2(fileName + ".png", file);
            }
        } else if (resultCode == 100) {
            getActivity().finish();
        } else if (resultCode == 200) {
            //重置内容
            text_project_name.setText("");
            edit_address.setText("");
            edit_title.setText("");
            edit_description.setText("");

            projectData = null;
            latitude = 0;
            longitude = 0;

            imageList.clear();
            bmpList.clear();
            addButton();
            adapter.notifyDataSetChanged();

        } else if (resultCode == 1000) {
            projectData = (QueryProjectBean.QueryProjectData) data.getSerializableExtra("bean");
            if (projectData != null) {
                text_project_name.setText(projectData.name);
            }
        }
    }

    private void dealBmp(Bitmap myBitmap) {
        if (index == 0) {
            before_far_bmp = myBitmap;
            image_before_far_1.setImageBitmap(myBitmap);
        } else if (index == 1) {
            before_near_bmp = myBitmap;
            image_before_near_1.setImageBitmap(myBitmap);
        } else if (index == 2) {
            after_far_bmp = myBitmap;
            image_after_far_1.setImageBitmap(myBitmap);
        } else if (index == 3) {
            after_near_bmp = myBitmap;
            image_after_near_1.setImageBitmap(myBitmap);
        }
    }

    private Bitmap before_far_bmp, before_near_bmp, after_far_bmp, after_near_bmp;
    private ImageUploadBean before_far_bean, before_near_bean, after_far_bean, after_near_bean;

    private void uploadPicIndex(String fileName, File file) {
        Map<String, String> headers = new HashMap<>();
        headers.put("authToken", SPHelper.getAuthToken());
        headers.put("from", "android");
        OkHttpUtils.post()
                .headers(headers)
                .addFile("file", fileName, file)
                .url(ApiDefine.UPLOAD_PIC)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("onError:", "onError");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("url:", response);
                        String jsonStr = response;
                        Gson gson = new GsonBuilder().create();
                        ImageUploadBean bean = gson.fromJson(jsonStr, new TypeToken<ImageUploadBean>() {
                        }.getType());

                        if (bean != null) {
                            if (index == 0) {
                                before_far_bean = bean;
                            } else if (index == 1) {
                                before_near_bean = bean;
                            } else if (index == 2) {
                                after_far_bean = bean;
                            } else if (index == 3) {
                                after_near_bean = bean;
                            }
                        }

                    }
                });
    }

    /**
     * 打开截图界面
     */
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }

        ClipImageActivity.goToClipActivity(getActivity(), uri, new ActivityResultHelper.Callback() {
            @Override
            public void onActivityResult(int resultCode, Intent intent) {
                if (intent == null) {
                    return;
                }

                final Uri uri = intent.getData();
                if (uri == null) {
                    return;
                }
                Bitmap myBitmap = PhotoUtils.getBitmapFromUri(uri, getActivity());

                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
                PictureUtil.saveMyBitmap(myBitmap, file);

                addBmp(myBitmap);

                uploadPic(fileName + ".png", file);
            }
        });
    }

    public void gotoClipActivity2(Uri uri) {
        if (uri == null) {
            return;
        }
        ClipImageActivity.goToClipActivity(getActivity(), uri, new ActivityResultHelper.Callback() {
            @Override
            public void onActivityResult(int resultCode, Intent intent) {
                if (intent == null) {
                    return;
                }

                if (intent == null) {
                    return;
                }

                final Uri uri = intent.getData();
                if (uri == null) {
                    return;
                }
                Bitmap myBitmap = PhotoUtils.getBitmapFromUri(uri, getActivity());

                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
                PictureUtil.saveMyBitmap(myBitmap, file);

                addBmp2(myBitmap);
                uploadPic2(fileName + ".png", file);
            }
        });
    }


    public void gotoClipActivityIndex(Uri uri) {
        if (uri == null) {
            return;
        }

        ClipImageActivity.goToClipActivity(getActivity(), uri, new ActivityResultHelper.Callback() {
            @Override
            public void onActivityResult(int resultCode, Intent intent) {
                if (intent == null) {
                    return;
                }

                final Uri uri = intent.getData();
                if (uri == null) {
                    return;
                }

                Bitmap myBitmap = PhotoUtils.getBitmapFromUri(uri, getActivity());

                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
                PictureUtil.saveMyBitmap(myBitmap, file);

                dealBmp(myBitmap);
                uploadPicIndex(fileName + ".png", file);
            }
        });
    }


    private ArrayList<ImageUploadBean> imageList = new ArrayList<>();
    private ArrayList<ImageUploadBean> imageAfterList = new ArrayList<>();

    private void uploadPic(String fileName, File file) {
        Map<String, String> headers = new HashMap<>();
        headers.put("authToken", SPHelper.getAuthToken());
        headers.put("from", "android");
        OkHttpUtils.post()
                .headers(headers)
                .addFile("file", fileName, file)
                .url(ApiDefine.UPLOAD_PIC)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("onError:", "onError");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("url:", response);
                        String jsonStr = response;
                        Gson gson = new GsonBuilder().create();
                        ImageUploadBean bean = gson.fromJson(jsonStr, new TypeToken<ImageUploadBean>() {
                        }.getType());

                        if (bean != null) {
                            imageList.add(bean);
                        }

                    }
                });
    }

    private QueryProjectBean.QueryProjectData projectData;

    private int projectType = 1;

    private void selectProjectType() {
        projectType = 1;
        Intent intent = new Intent(getActivity(), ProjectListActivity.class);
        intent.putExtra("latitude", latitude);
        intent.putExtra("longitude", longitude);
        startActivityForResult(intent, 1000);
    }

    /**
     * 删除图片
     */
    private void deletePic(int position) {
        imageList.remove(position);
        bmpList.remove(position);

        adapter.notifyDataSetChanged();
    }

    /**
     * 添加按钮
     */
    private void addButton() {
        ImageBean bean = new ImageBean();
        bean.type = 0;
        bmpList.add(bean);

        adapter.notifyDataSetChanged();
    }

    /**
     * 添加图片
     */
    private void addBmp(Bitmap bmp) {
        ImageBean bean = new ImageBean();
        bean.bitmap = bmp;
        bean.path = StringUtils.bitmaptoString(bmp);
        bean.type = 1;
        bmpList.add(bmpList.size() - 1, bean);

        adapter.notifyDataSetChanged();
    }

    /**
     * 删除图片
     */
    private void deletePic2(int position) {
        imageAfterList.remove(position);
        bmpAfterList.remove(position);

        afterAdapter.notifyDataSetChanged();
    }

    /**
     * 添加按钮
     */
    private void addButton2() {
        ImageBean bean = new ImageBean();
        bean.type = 0;
        bmpAfterList.add(bean);

        afterAdapter.notifyDataSetChanged();
    }

    /**
     * 添加图片
     */
    private void addBmp2(Bitmap bmp) {
        ImageBean bean = new ImageBean();
        bean.bitmap = bmp;
        bean.path = StringUtils.bitmaptoString(bmp);
        bean.type = 1;
        bmpAfterList.add(bmpAfterList.size() - 1, bean);

        afterAdapter.notifyDataSetChanged();
    }

    private void uploadPic2(String fileName, File file) {
        Map<String, String> headers = new HashMap<>();
        headers.put("authToken", SPHelper.getAuthToken());
        headers.put("from", "android");
        OkHttpUtils.post()
                .headers(headers)
                .addFile("file", fileName, file)
                .url(ApiDefine.UPLOAD_PIC)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("onError:", "onError");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("url:", response);
                        String jsonStr = response;
                        Gson gson = new GsonBuilder().create();
                        ImageUploadBean bean = gson.fromJson(jsonStr, new TypeToken<ImageUploadBean>() {
                        }.getType());

                        if (bean != null) {
                            imageAfterList.add(bean);
                        }

                    }
                });
    }

    private GeoPoint geoPoint;
    private double latitude, longitude;


    private void initLocation() {
        edit_address.setText(currentPlaceName);
//        geoPoint = RoundFragment.mMyLocation.getMyLocation();
//
//        latitude = geoPoint.getLatitudeE6();
//        longitude = geoPoint.getLongitudeE6();
//
//        //逆地理编码类，根据输入的点坐标，返回相应的地理信息
//        TGeoDecode tGeoDecode = new TGeoDecode(new OnGeoResultListener());
//        tGeoDecode.search(geoPoint);
    }

    class MyOverlay extends MyLocationOverlay {
        public MyOverlay(Context context, MapView mapView) {
            super(context, mapView);
        }

        /*
         * 处理在"我的位置"上的点击事件
         */
        protected boolean dispatchTap() {
            return true;
        }

        @Override
        public void onLocationChanged(Location location) {
            super.onLocationChanged(location);
        }
    }

    /**
     * 逆地理编码回调结果监听
     */
    class OnGeoResultListener implements TGeoDecode.OnGeoResultListener {

        @Override
        public void onGeoDecodeResult(TGeoAddress tGeoAddress, int errorCode) {

            if (TErrorCode.OK == errorCode) {
                // 查询点相关信息
                edit_address.setText(tGeoAddress.getFullName());
            } else {
                ToastUtils.showText(getActivity(), "位置查询出错，请稍后重试");
            }
        }
    }

    /**
     * 1
     * 获取定位
     */
    public void getLocationInfo() {
        initLocation();
    }

    private PoiSearch mPoiSearch;

    /**
     * 根据地址查询经纬度
     */
    private void getLatLng(String address) {
        mPoiSearch = new PoiSearch(getActivity(), new OnGetPoiResultListener() {
            @Override
            public void OnGetPoiResult(ArrayList<PoiInfo> arrayList, ArrayList<PoiSearch.ProvinceInfo> arrayList1, String s, int i) {
                if (arrayList != null && arrayList.size() > 0) {
                    longitude = arrayList.get(0).mPoint.getLongitudeE6();
                    latitude = arrayList.get(0).mPoint.getLatitudeE6();

                    uploadData();
                } else {
                    ToastUtils.showText(getActivity(), "请输入正确的地址信息");
                    edit_address.requestFocus();
                    Utils.showSoftInputFromWindow(edit_address);
                }
            }
        }, RoundFragment.mMapView);
        mPoiSearch.search(address, null, null);
    }

    /**
     * 获取图片url
     */
    private String getImageListStr() {
        JSONArray jsonArray = new JSONArray();

        for (int i = 0; i < imageList.size(); i++) {
            ImageUploadBean bean = imageList.get(i);

            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("groupName", bean.groupName);
                jsonObject.put("photoType", bean.extName);
                jsonObject.put("photoUrl", bean.fileName);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonArray.put(jsonObject);
        }

        return jsonArray.toString();
    }

    private String getImageListStr2() {
        JSONArray jsonArray = new JSONArray();

        for (int i = 0; i < imageAfterList.size(); i++) {
            ImageUploadBean bean = imageAfterList.get(i);

            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("fileOwn", "afterUrl");
                jsonObject.put("groupName", bean.groupName);
                jsonObject.put("extName", bean.extName);
                jsonObject.put("fileName", bean.fileName);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonArray.put(jsonObject);
        }

        return jsonArray.toString();
    }


    /**
     * 获取问题编号
     */
    private void getProblemNumber() {
        GsonRequestHelper helper = new GsonRequestHelper(getActivity());
        Map<String, String> params = new HashMap<>();

        helper.sendPOSTRequest(ApiDefine.GETNUMBER, BaseBean.class, params, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    BaseBean bean = (BaseBean) data;

                    if (bean.code.equals("0")) {
//                        text_serialNumber.setText(bean.msg);
                    } else {
                    }
                }
            }
        });
    }


    /**
     * 新增
     */
    private void uploadData() {
        if (TextUtils.isEmpty(edit_title.getText().toString())) {
            ToastUtils.showText(getActivity(), "请输入问题标题");
            edit_title.requestFocus();
            Utils.showSoftInputFromWindow(edit_title);
            return;
        }

        if (TextUtils.isEmpty(edit_address.getText().toString())) {
            ToastUtils.showText(getActivity(), "请输入地址");
            edit_address.requestFocus();
            Utils.showSoftInputFromWindow(edit_address);
            return;
        }

        if (isSelfDeal) {
            if (imageList.size() < 2) {
                ToastUtils.showText(getActivity(), "请至少上传处置前一张远景照片和一张近景照片");
                return;
            }

            if (imageAfterList.size() == 1) {
                ToastUtils.showText(getActivity(), "请至少上传处置后一张远景照片和一张近景照片");
                return;
            }
        }

//        if (TextUtils.isEmpty(text_big_type.getText().toString())) {
//            ToastUtils.showText(getActivity(), "请选择问题大类");
//            return;
//        }
//
//        if (TextUtils.isEmpty(text_small_type.getText().toString())) {
//            ToastUtils.showText(getActivity(), "请选择问题小类");
//            return;
//        }

//        if (TextUtils.isEmpty(textRegion.getText().toString())) {
//            ToastUtils.showText(getActivity(), "请选择所属地区");
//            return;
//        }

        if (projectData == null) {
            ToastUtils.showText(getActivity(), "请选择关联项目");
            return;
        }

        GsonRequestHelper helper = new GsonRequestHelper(getActivity());
        Map<String, String> params = new HashMap<>();
        params.put("reportPlace", edit_address.getText().toString());
        params.put("description", edit_description.getText().toString());
        params.put("latitude", latitude + "");
        params.put("longitude", longitude + "");
        Log.e("latitude1", latitude + "");
        Log.e("longitude1", longitude + "");
        Log.e("latitude", Utils.formatLatLng((float) (latitude / 1E6)));
        Log.e("longitude", Utils.formatLatLng((float) (longitude / 1E6)));
        params.put("photographer", SPHelper.getUid());
        params.put("problemSort", "1");
        params.put("problemType", getProblemBigType().get(0).dictValue);
//        params.put("problemClass", LinhuApp.problemSmallTypeList.get(smallPos).dictValue);
        params.put("areaName", textRegion.getText().toString());

        if (projectData != null) {
            params.put("projectId", projectData.id);
            params.put("projectName", projectData.name);
            params.put("projectType", projectType + "");
        }
//        params.put("serialNumber", text_serialNumber.getText().toString());
        params.put("title", edit_title.getText().toString());
        params.put("problemPhotoUrls", getImageListStr());
        params.put("description", edit_description.getText().toString());

        if (isSelfDeal) {
            params.put("deelFlag", "1");
            params.put("remark", edit_remark.getText().toString());
            params.put("afterUrl", getImageListStr2());
        } else {
            params.put("deelFlag", "0");
        }

        helper.sendPOSTRequest(ApiDefine.PROBLEM_ADD, BaseBean.class, params, true, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    BaseBean bean = (BaseBean) data;

                    if (bean.code.equals("0")) {
                        Intent intent = new Intent(getActivity(), UploadSuccessActivity.class);
                        startActivityForResult(intent, 100);
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(getActivity());
                    } else {
                        ToastUtils.showText(getActivity(), bean.msg);
                    }
                }
            }
        });
    }

    private int regionPos;
    private int bigPos;
    private int smallPos;

    private PopupWindow popupWindow;

    private void showDict(View view, final String tag) {
        if (popupWindow != null && popupWindow.isShowing()) {
            return;
        }
        RelativeLayout layout = (RelativeLayout) getLayoutInflater().inflate(R.layout.pop_dict, null);
        popupWindow = new PopupWindow(layout,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        // 产生背景变暗效果
        WindowManager.LayoutParams lp = getActivity().getWindow()
                .getAttributes();
        lp.alpha = 0.4f;
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getActivity().getWindow().setAttributes(lp);


        //点击空白处时，隐藏掉pop窗口
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //添加弹出、弹入的动画
        popupWindow.setAnimationStyle(R.style.Popupwindow3);
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        popupWindow.showAtLocation(view, Gravity.LEFT | Gravity.BOTTOM, 0, -location[1]);
        //添加按键事件监听
        setButtonListeners(layout, tag);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            // 在dismiss中恢复透明度
            public void onDismiss() {
                WindowManager.LayoutParams lp = getActivity().getWindow()
                        .getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getActivity().getWindow().setAttributes(lp);
            }
        });
    }

    private void setButtonListeners(RelativeLayout layout, final String tag) {
        TextView text_cancel = layout.findViewById(R.id.text_cancel);
        TextView text_ok = layout.findViewById(R.id.text_ok);
        final WheelView wheelview = layout.findViewById(R.id.wheelview);

        text_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        text_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

                if (tag.equals("region")) {
                    regionPos = wheelview.getSelectedItemPosition();
                    textRegion.setText(LinhuApp.regionList.get(regionPos).name);
                } else if (tag.equals("big")) {
                    bigPos = wheelview.getSelectedItemPosition();
                    text_big_type.setText(LinhuApp.problemTypeList.get(bigPos).dictLabel);

                    problemSmallType(LinhuApp.problemTypeList.get(bigPos).dictValue);
                } else if (tag.equals("small")) {
                    smallPos = wheelview.getSelectedItemPosition();
                    text_small_type.setText(LinhuApp.problemSmallTypeList.get(smallPos).dictLabel);
                }
            }
        });

        //设置数据
        if (tag.equals("region")) {
            wheelview.setData(LinhuApp.regionList);
        } else if (tag.equals("big")) {
            wheelview.setData(getProblemBigType());
        } else if (tag.equals("small")) {
            wheelview.setData(LinhuApp.problemSmallTypeList);
        }

        //尽请使用各种方法
        wheelview.setTextSize(20f, true);
        wheelview.setNormalItemTextColor(0xff666666);
        wheelview.setSelectedItemTextColor(0xff000000);
        wheelview.setDividerPaddingForWrap(13f);

        if (tag.equals("region")) {
            wheelview.setSelectedItemPosition(regionPos);
        } else if (tag.equals("big")) {
            wheelview.setSelectedItemPosition(bigPos);
        } else if (tag.equals("small")) {
            wheelview.setSelectedItemPosition(smallPos);
        }
    }

    /**
     * 获取大类
     */
    public List<DictBean.DictData> getProblemBigType() {
        List<DictBean.DictData> list = new ArrayList<>();

        for (DictBean.DictData data : LinhuApp.problemTypeList) {
            if (data.dictLabel.equals("建设管理方面")) {
                list.add(data);
            }
        }

        return list;
    }


    /**
     * 获取小类
     */
    public void problemSmallType(String dictDataValue) {
        GsonRequestHelper helper = new GsonRequestHelper(getActivity());
        Map<String, String> params = new HashMap<>();
        params.put("dictDataValue", dictDataValue);
        params.put("dictDataType", "problem_type");

        helper.sendPOSTRequest(ApiDefine.PROBLEM_DICT_SMALL, DictBean.class, params, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    DictBean bean = (DictBean) data;

                    if (bean.code.equals("0")) {
                        List<DictBean.DictData> list = bean.rows;
                        if (list != null && list.size() > 0) {
                            LinhuApp.problemSmallTypeList.clear();
                            LinhuApp.problemSmallTypeList.addAll(list);

                            if (LinhuApp.problemSmallTypeList.size() > 0) {
                                smallPos = 0;
                                text_small_type.setText(LinhuApp.problemSmallTypeList.get(smallPos).dictLabel);
                            } else {
                                smallPos = 0;
                                text_small_type.setText("");
                            }
                        }
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(getActivity());
                    } else {

                    }
                }
            }
        });
    }

}
